<template>
  <!--面包屑导航-->
  <el-row style="margin: 5px 5px;">
    <el-col :span="24">
      <el-breadcrumb :separator-icon="ArrowRight">
        <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>主数据</el-breadcrumb-item>
        <el-breadcrumb-item>物料产品分类</el-breadcrumb-item>
      </el-breadcrumb>
    </el-col>
  </el-row>

  <!--查询条件区-->
  <el-row style="margin: 5px 5px;">
    <el-col :span="24">
      <el-form :model="searchItemType" style="margin: 15px 0" inline>
        <el-form-item label="分类名称">
          <el-input v-model="searchItemType.itemTypeName" placeholder="请输入分类名称" />
        </el-form-item>
        <!--是否启用-->
        <el-form-item label="是否启用">
          <el-select v-model="searchItemType.enableFlag" placeholder="请选择是否启用" style="width: 100px;">
            <el-option label="全部" :value="null" />
            <el-option label="是" :value="1" />
            <el-option label="否" :value="2" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button @click="fetchItemTypeList" type="primary">搜索</el-button>
        </el-form-item>
        <el-form-item>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </el-col>
  </el-row>

  <!--表格主题-->
  <el-row style="margin: 5px 5px;">
    <el-col :span="24">
      <el-table
          :data="itemTypeList"
          border
          stripe
          row-key="itemTypeId"
          lazy
          :load="loadChildrenTask"
          :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
      >
        <el-table-column prop="itemTypeName" label="分类名称" />
        <el-table-column prop="orderNum" label="排序" />
        <el-table-column prop="itemOrProduct" label="物料/产品" />
        <el-table-column prop="enableFlag" label="是否启用" width="120">
          <template #default="scope">
            <el-tag type="success" v-if="scope.row.enableFlag == 1">是</el-tag>
            <el-tag type="danger" v-else-if="scope.row.enableFlag == 2">否</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" />
        <el-table-column label="操作">
          <template #default="scope">
            <el-button type="primary" @click="handleEdit(scope.row)">修改</el-button>

            <el-button type="success" @click="handleAdd(scope.row)">新增</el-button>
            <el-button type="danger" @click="handleDelete(scope.row)">删除</el-button>



          </template>
        </el-table-column>
      </el-table>
    </el-col>
  </el-row>
  <!-- 编辑物料分类弹窗 -->
  <el-dialog
      v-model="dialogItemTypeEditVisiable"
      title="编辑物料分类"
  >
    <el-row :gutter="24">
      <el-form v-model="loadItemTypeInfo" size="medium" label-width="100px">
        <el-col :span="24">
          <el-form-item label="父分类" >
            <el-input v-model="loadItemTypeInfo.parentItemTypeName" placeholder="顶层节点没有父分类" readonly :style="{width: '100%'}" />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="分类名称">
            <el-input v-model="loadItemTypeInfo.itemTypeName" placeholder="请输入分类名称" clearable :style="{width: '100%'}" />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="显示排序">
            <el-input-number v-model="loadItemTypeInfo.orderNum" placeholder="显示排序"></el-input-number>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="物料/产品">
            <el-radio-group v-model="loadItemTypeInfo.itemOrProduct">
              <el-radio :value="'item'" label="物料"/>
              <el-radio :value="'product'" label="产品"/>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="启用状态">
            <el-radio-group v-model="loadItemTypeInfo.enableFlag" size="medium">
              <el-radio :value="'1'" label="是"/>
              <el-radio :value="'2'" label="否"/>
            </el-radio-group>
          </el-form-item>
        </el-col>
      </el-form>
    </el-row>

    <!-- 弹窗底部的按钮 -->
    <template #footer>
      <el-button @click="handleClose">取消</el-button>
      <el-button type="primary" @click="submitUpdataForm(loadItemTypeInfo)">确定</el-button>
    </template>
  </el-dialog>

<!--   新增物料分类弹窗-->
  <el-dialog
      v-model="dialogItemTypeAddVisiable"
      title="新增物料分类"
  >
    <el-row :gutter="24">
      <el-form v-model="loadItemTypeInfo" size="medium" label-width="100px">
        <el-col :span="24">
          <el-form-item label="父分类" >
            <el-input v-model="loadItemTypeInfo.parentItemTypeName" placeholder="顶层节点没有父分类" readonly :style="{width: '100%'}" />

          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="分类名称">
            <el-input v-model="loadItemTypeInfo.itemTypeName"  aria-required="true" placeholder="请输入分类名称" clearable :style="{width: '100%'}" />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="显示排序">
            <el-input-number v-model="loadItemTypeInfo.orderNum" placeholder="显示排序"></el-input-number>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="物料/产品">
            <el-radio-group v-model="loadItemTypeInfo.itemOrProduct">
              <el-radio :value="'item'" label="物料"/>
              <el-radio :value="'product'" label="产品"/>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="启用状态">
            <el-radio-group v-model="loadItemTypeInfo.enableFlag" size="medium">
              <el-radio :value="'1'" label="是"/>
              <el-radio :value="'2'" label="否"/>
            </el-radio-group>
          </el-form-item>
        </el-col>
      </el-form>
    </el-row>
    <!-- 弹窗底部的按钮 -->
    <template #footer>
      <el-button @click="handleClose">取消</el-button>
      <el-button type="primary" @click="submitSavaForm(loadItemTypeInfo)">确定</el-button>
    </template>
  </el-dialog>

</template>

<script setup>
import { ref, onMounted } from 'vue';
import itemTypeRequest from '@/api/md/item/itemType.js';
import {ElMessage} from "element-plus";
const dialogItemTypeEditVisiable = ref(false) // 控制弹窗的显示与隐藏
const dialogItemTypeAddVisiable = ref(false)// 控制新增物料分类弹窗的显示与隐藏

// 查询条件
const searchItemType = ref({
  itemTypeName: '',  // 分类名称
  enableFlag: null   // 启用状态 (null: 全部, 1: 是, 2: 否)
});

// 物料分类列表
const itemTypeList = ref([]);

// 查询物料分类列表
const fetchItemTypeList = () => {
  itemTypeRequest.loadItemTypeList(searchItemType.value, res => {
    itemTypeList.value = buildTree(res.data || []);
  });
};

// 修改物料分类弹窗内部根据id查询对应物料分类
let loadItemTypeInfo = ref({});
let loadItemTypeParentInfo = ref({});
let tempItemTypeId = ref({});
const now = new Date();

const year = now.getFullYear();
const month = ('0' + (now.getMonth() + 1)).slice(-2);
const day = ('0' + now.getDate()).slice(-2);
const hours = ('0' + now.getHours()).slice(-2);
const minutes = ('0' + now.getMinutes()).slice(-2);
const seconds = ('0' + now.getSeconds()).slice(-2);

const formattedTime = year + "-" + month + "-" + day + " " +  hours + ":" + minutes + ":" + seconds;
const templateItemType = ref({
  parentTypeId: null,
  itemTypeName: null,
  orderNum: null,
  itemOrProduct: null,
  enableFlag: null,
  //创建时间为当前时间
  createTime: formattedTime,
  ancestors: 1,
  itemStatus: 1,
  parentItemTypeName: null,
});

// 构建树形结构
const buildTree = (flatList) => {
  const map = new Map();
  const tree = [];

  // 将所有项放入 map 中
  flatList.forEach((item) => {
    map.set(item.itemTypeId, { ...item, children: [] });
  });

  // 建立父子关系
  flatList.forEach((item) => {
    if (item.parentTypeId) {
      const parent = map.get(item.parentTypeId);
      if (parent) {
        parent.children.push(map.get(item.itemTypeId));
      }
    } else {
      tree.push(map.get(item.itemTypeId));
    }
  });

  return tree;
};

// 重置查询条件
const resetSearch = () => {
  searchItemType.value = { itemTypeName: '', enableFlag: null };
  fetchItemTypeList();
};

// 编辑物料分类
function handleEdit(row){
  console.log("修改分类", row.itemTypeId);
  itemTypeRequest.loadUpdateInfo(row,res=>{
    loadItemTypeInfo.value = res.data[0]
    dialogItemTypeEditVisiable.value = true // 显示弹窗
    console.log(loadItemTypeInfo.value)
  })
  // 编辑逻辑
};

//将修改的表单数据进行提交
function submitUpdataForm(itemTypeInfo){
  console.log(itemTypeInfo)
  itemTypeRequest.EditDateSubmit(itemTypeInfo, res => {
    console.log(res)
    if (res.code == 200) {
      ElMessage({
        type: "success",
        message: "添加成功"
      })
      loadDeviceTypes('F');
      cancelInsert();
    } else {
      ElMessage({
        type: "error",
        message: "添加失败"
      })
    }

  })
}

//将新增的表单数据进行提交
function submitSavaForm(itemTypeInfo){
  console.log(itemTypeInfo)
  itemTypeRequest.saveItemType(itemTypeInfo, res => {
    console.log(res)
    if (res.code == 200) {
      ElMessage({
        type: "success",
        message: "添加成功"
      })
      loadDeviceTypes('F');
      cancelInsert();
    } else {
      ElMessage({
        type: "error",
        message: "添加失败"
     })
    }
  })
}

// 关闭弹窗
const handleClose = () => {
  dialogItemTypeEditVisiable.value = false // 隐藏弹窗
  dialogItemTypeAddVisiable.value = false
}

//新增物料分类
function handleAdd(row){
  console.log("新增分类", row.itemTypeId);
  itemTypeRequest.loadUpdateInfo(row, res => {
    templateItemType.value.parentItemTypeName = res.data[0].itemTypeName
    templateItemType.value.parentTypeId = res.data[0].itemTypeId
    loadItemTypeInfo.value = templateItemType.value

    console.log(loadItemTypeInfo.value)
  })
  dialogItemTypeAddVisiable.value = true;
  // 新增逻辑
};

// 删除物料分类
function handleDelete(row){
  console.log("删除分类", row.itemTypeId);
  itemTypeRequest.isParentItemType(row.itemTypeId, res => {
    console.log(res.code)
    if (res.code > 0) {
      ElMessage({
        type: "error",
        message: "该分类下有子分类，无法删除"
      })
    } else {
      itemTypeRequest.deleteItemType(row.itemTypeId, res => {
        if (res.code == 200) {
          ElMessage({
            type: "success",
            message: "删除成功"
          })
          fetchItemTypeList();
        } else {
          ElMessage({
            type: "error",
            message: "删除失败"
          })
        }
      })
    }
  })
};

// 加载子分类数据
const loadChildrenTask = (itemType, node, resolve) => {
  const childrenSearch = {
    ...searchItemType.value,
    ancestors: 1,
    parentId: itemType.itemTypeId,
  };
  itemTypeRequest.loadItemTypeList(childrenSearch, res => {
    const children = buildTree(res.data || []);
    resolve(children);
  });
};

//加载通过id获取的用于修改物料分类信息


// 初始化加载物料分类列表
onMounted(() => {
  fetchItemTypeList();
});
</script>
